package com.hm.health.Activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;

import com.goodix.RxProgressDialog.RxProgressSubscribe;
import com.goodix.http.HttpConstants;
import com.goodix.http.RawDataManager;
import com.goodix.http.UserConfigManager;
import com.goodix.http.jsonparams.response.LoginResponse;
import com.goodix.ini.HbdOptionIni;
import com.goodix.ini.IniFileUtils;
import com.goodix.utils.DefaultSpUtil;
import com.goodix.utils.MPermissionUtils;
import com.goodix.utils.SPUtils;
import com.goodix.utils.ToastUtils;
import com.goodix.widget.AlertDialogEx;
import com.google.android.material.textfield.TextInputLayout;
import com.hm.health.MyApplication;
import com.hm.health.R;
import com.hm.health.Utils.FileUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;

public class LoginActivity extends BaseActivity {

    private static final String KEY_USER_NAME = "user_name";
    private static final String KEY_USER_PASSWORD = "user_password";
    private static final String USER_NAME_DEFAULT = "";
    private static final String USER_PASSWORD_DEFAULT = "";

    private static final String TAG = "LoginUserActivity";
    @BindView(R.id.user_name)
    EditText mUserNameEdit;
    @BindView(R.id.user_name_fram)
    TextInputLayout mUserNameFramTil;
    @BindView(R.id.user_passwd)
    EditText mUserPasswdEdit;
    @BindView(R.id.ueser_passwd_fram)
    TextInputLayout mUeserPasswdFramTil;
    @BindView(R.id.btn_login)
    Button mBtnLogin;
    @BindView(R.id.tv_offline_use)
    TextView mTvOfflineUse;

    String mUserName;
    String mUserPassword;
    private Subscription mSubscription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        MyApplication.getInstance().addActivity(this);
        initActionBar();
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }

        fillUserInfos();
        requestPermission();
    }

    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(false);
        setCenterTitle(R.string.app_name);
        actionBar.setDisplayHomeAsUpEnabled(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if ((null != mSubscription) && (!mSubscription.isUnsubscribed())) {
            mSubscription.unsubscribe();
        }
    }

    public void fillUserInfos() {
        mUserName = (String) SPUtils.get(getApplicationContext(), KEY_USER_NAME, USER_NAME_DEFAULT);
        mUserPassword = (String) SPUtils.get(getApplicationContext(), KEY_USER_PASSWORD, USER_PASSWORD_DEFAULT);

        if (null != mUserName && !mUserName.isEmpty()) {
            mUserNameEdit.setText(mUserName);
        }

        if (null != mUserPassword && !mUserPassword.isEmpty()) {
            mUserPasswdEdit.setText(mUserPassword);
        }
    }

    @OnClick({R.id.btn_login, R.id.tv_offline_use})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                checkAndLogin();
                break;
            case R.id.tv_offline_use:
                startActivity();
                break;
        }
    }

    private void checkAndLogin() {
        if (!checkUserInfo()) {
            ToastUtils.showShortToastMessage(getApplicationContext(), getString(R.string.enter_valid_user_info));
        } else {
            mBtnLogin.setEnabled(false);
            login();
        }
    }

    private boolean checkUserInfo() {
        mUserName = mUserNameEdit.getText().toString();
        mUserPassword = mUserPasswdEdit.getText().toString();

        // 用户名不同，删除本地驱动配置
        String userName = "NULL";
        userName = (String) SPUtils.get(getApplicationContext(), KEY_USER_NAME, userName);
        if (mUserName.compareTo(userName) != 0) {
            DefaultSpUtil.cleanSharedPreference(mContext);
        }

        // 删除本地驱动配置和UI配置
        FileUtil.deleteDir(IniFileUtils.getDeviceConfigPath(mContext));
        FileUtil.deleteDir(IniFileUtils.getHbdOptionIniPath(mContext));

        return !(null == mUserName || mUserName.isEmpty() || null == mUserPassword || mUserPassword.isEmpty());
    }

    private void login() {
        mSubscription = UserConfigManager.login(mUserName, mUserPassword, this)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxProgressSubscribe<>(getString(R.string.in_logining), new Observer<LoginResponse>() {
                    @Override
                    public void onNext(LoginResponse response) {
                        Log.i(TAG, "login onNext------------------");
                        mBtnLogin.setEnabled(true);
                        if (null != response && response.getStatus() == HttpConstants.RESULT_STATUS_SUCCESS) {
                            Log.i(TAG, "token: " + response.getToken() + ";  key : " + response.getKey());
                            SharedPreferences preferences = getSharedPreferences(HttpConstants.SHARED_PREFRENCE_NAME_USER, Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.putString(HttpConstants.SHARED_PREFRENCE_KEY_USERKEY, response.getKey());
                            editor.putLong(HttpConstants.SHARED_PREFRENCE_KEY_USERTOKEN, response.getToken());
                            editor.putString(HttpConstants.SHARED_PREFRENCE_KEY_USERNAME, mUserName);
                            editor.commit();
                            MyApplication.getInstance().setLoginResponse(response);
                            RawDataManager.setUserAndToken(mUserName, response.getToken());
                            saveUserInfo();
                            startActivity();
                        } else if (null != response && response.getStatus() == HttpConstants.RESULT_STATUS_NET_ERROR) {
                            mUeserPasswdFramTil.setError(getString(R.string.login_hint));
                        } else {
                            mUeserPasswdFramTil.setError(getString(R.string.login_failed_hint));
                        }
                    }

                    @Override
                    public void onCompleted() {
                        mBtnLogin.setEnabled(true);
                        Log.i(TAG, "login onCompleted------------------");
                    }

                    @Override
                    public void onError(Throwable e) {
                        mBtnLogin.setEnabled(true);
                        mUeserPasswdFramTil.setError(getString(R.string.login_hint));
                        Log.e(TAG, "login onError------------------" + e);
                    }
                }, this));
    }

    private void saveUserInfo() {
        MyApplication.setUserName(mUserName);
        SPUtils.put(getApplicationContext(), KEY_USER_NAME, mUserName);
        SPUtils.put(getApplicationContext(), KEY_USER_PASSWORD, mUserPassword);
    }

    private void requestPermission() {
        MPermissionUtils.requestPermissionsResult(LoginActivity.this, 1,
                MPermissionUtils.PERMISSIONS_WITH_BLE,
                new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        Log.i(TAG, "onPermissionGranted");
                    }

                    @Override
                    public void onPermissionDenied() {
                        finish();
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void startActivity() {
        HbdOptionIni optionIni = null;
        try {
            optionIni = IniFileUtils.loadHBDOptionIni(mContext);
        } catch (Exception e) {
            AlertDialogEx.Builder builder = new AlertDialogEx.Builder(mContext);
            builder.setMessage(e.getMessage());
            builder.setNegativeButton(R.string.quit, view -> MyApplication.getInstance().exit());
            builder.show();
            return;
        }
        MyApplication.setHbdOptionIni(optionIni);
        Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
        startActivity(intent);
    }
}
